package com.utils;

import com.config.ContextUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/5/4 0:25
 * @since JDK 1.8
 *
 * 数据库连接配置
 */
public class ConnectionUtils {

    private Connection conn = null;

    public Connection getSysTemConnection(){
        Map<String, String> sqlMaps= ContextUtils.getBeanObj("sql");
        String driver = (String) sqlMaps.get("driver");
        String url = (String) sqlMaps.get("url");
        String username = (String) sqlMaps.get("username");
        String passwrod = (String) sqlMaps.get("password");
        return createConnection(driver,url,username,passwrod);
    }



    public Connection createConnection(String driver,String url,String username,String password){
        try{
            //获取连接对象Connection
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
            close();
        }
        return conn;
    }

    private void close(){
        try{
            conn.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
